package com.cqupt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cqupt.mapper.TriggerMapper;
import com.cqupt.pojo.Problem;
import com.cqupt.pojo.Trigger;
import com.cqupt.service.TriggerService;
import com.cqupt.utils.APIUtils;
import com.cqupt.utils.TextUtils;
import com.cqupt.utils.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class TriggerServiceImpl implements TriggerService {
    @Autowired
    private TriggerMapper triggerMapper;

    public TriggerMapper getTriggerMapper() {
        return triggerMapper;
    }

    public void setTriggerMapper(TriggerMapper triggerMapper) {
        this.triggerMapper = triggerMapper;
    }

    @Override
    public Trigger selectTranslatedTrigger(Long hostId) {
        return triggerMapper.findTriggerById(hostId);
    }

    /**
     * 获取指定监控项的所有触发器
     * @param itemId 监控项id
     * @param token 令牌
     * @return
     */
    @Override
    public List<Map<String, Object>> getAllTriggersByItemid(final String itemId,final String token) {
//        String[] attrs = new String[]{"triggerid","description","priority","opdata","expression","value","status"};
        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "trigger.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("itemids", itemId);
                put("expandExpression","true");
                put("output","extend");
                put("selectDependencies","extend");
                put("selectFunctions","extend");
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>)responseMap.get("result");
    }

    /**
     * 获取指定主机的所有触发器
     * @param hostId
     * @param token
     * @return
     */
    @Override
    public List<Map<String, Object>> getAllTriggersByHostid(String hostId, String token) {
        // 针对于触发器的汉化翻译
        Map<String, String> initHostItem = TextUtils.getTriggerDataToMap();
        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "trigger.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids", hostId);
                put("expandExpression","true");
                put("output", "extend");
                put("selectDependencies","extend");
                put("selectFunctions","extend");
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        //对数据进行翻译封装
        for (int i = 0; i < resultList.size(); i++) {
            Map<String, Object> stringObjectMap = resultList.get(i);
            String name = (String) stringObjectMap.get("description");
            stringObjectMap.put("description", initHostItem.get(name)==null?name:initHostItem.get(name));
        }
        return (List<Map<String, Object>>)responseMap.get("result");
    }

    /**
        * @param triggerid
	    * @param token
        * @return Map<String,Object>
        * @Description Return only templates that contain the given triggers.
        * @date 2020/12/9 14:15
    */
    @Override
    public Map<String, Object> getTempByTriggerId(String triggerid, String token) {
        List<String> output = new ArrayList();
        output.add("templateid");
        output.add("name");

        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc","2.0");
            put("method", "template.get");
            put("auth", token);
            put("id", 1);

            // 参数
            put("params",new HashMap<String,Object>(){{
                put("filter",new HashMap<String,Object>(){{
                    put("triggerids",triggerid);
                }});
                put("output",output);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }
    /**
     * @Description //创建触发器告警项
     * @Date 9:10 2020/12/11
     * @Param
     **/
    @Override
    public Map<String,Object> createTrigger(Map<String, Object> triggerNews) {
        String token = APIUtils.getToken();
        Map<String,Object> paramsMap = new HashMap<String,Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "trigger.create");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("description",triggerNews.get("description"));
                put("expression",triggerNews.get("expression"));
                put("priority",triggerNews.get("priority"));
                put("comments",triggerNews.get("comments"));
                put("status",triggerNews.get("status"));
                put("manual_close",triggerNews.get("manual_close"));
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Map<String,Object> result = (Map<String, Object>) responseMap.get("result");
        // 封装返回结果
        Map<String, Object> returnNews = new HashMap<>();
        if (result == null){
            Map<String,Object> error = (Map<String, Object>) responseMap.get("error");
            String data = error.get("data").toString();
            returnNews.put("flag",false);
            returnNews.put("message",data);
        }else {
            String triggerids = ((List<String>)result.get("triggerids")).get(0);
            returnNews.put("flag",true);
            returnNews.put("message",triggerids);
        }
        return returnNews;
    }
/**
* @Description //根据triggerID删除监控项
* @Date 9:55 2020/12/14
* @Param [triggerIds]
**/
    @Override
    public Map<String, Object> deleteTrigger(List<String> triggerIds) {
        String token = APIUtils.getToken();
        Map<String,Object> paramsMap = new HashMap<String,Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "trigger.delete");
            put("id", 1);
            put("params",triggerIds);
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Map<String,Object> result = (Map<String, Object>) responseMap.get("result");
        Map<String, Object> returnNews = new HashMap<>();
        if (result == null){
            Map<String,Object> error = (Map<String, Object>) responseMap.get("error");
            String data = error.get("data").toString();
            //String massage = "未找到相关监控项";
            returnNews.put("flag",false);//删除失败，返回false的信息
            returnNews.put("message",data);
        }else {
            //返回删除的告警项ID（triggerids）
            //List<String> triggerids = (List<String>)result.get("triggerids");
            returnNews.put("flag",true);//删除成功，返回true的信息
            //returnNews.put("triggerids",triggerids);
            returnNews.put("message","删除成功！");
        }
        return returnNews;
    }

    /**
    * @param triggerid
    * @param status
    * @return java.util.Map<java.lang.String,java.lang.Object>
    * @Description
    * @date 2020/12/14 15:24
    */
    @Override
    public Map<String, Object> updateTrigger(final String triggerid,final String status) {
        String token = APIUtils.getToken();
        Map<String,Object> paramsMap = new HashMap<String,Object>(){{
            put("jsonrpc","2.0");
            put("method","trigger.update");
            put("params",new HashMap<String,Object>(){{
                put("triggerid",triggerid);
                put("status",status);
            }});
            put("auth",token);
            put("id",1);
        }};

        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }

    /**
     * 更具id获取全部触发器信息
     * @param triggerid
     * @return
     */
    public Map<String, Object> getTriggerByID(String triggerid){
       String token = APIUtils.getToken();
        List<String> output = new ArrayList<>();
        output.add("expression");
        Map<String,Object> paramsMap = new HashMap<String,Object>(){{
            put("jsonrpc","2.0");
            put("method","trigger.get");
            put("params",new HashMap<String,Object>(){{
                put("output",output);
                put("triggerids",triggerid);
                put("expandExpression","true");
            }});
            put("auth",token);
            put("id",1);
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }

    /**
     * 触发器函数新
     * @param hostId
     * @param token
     * @return
     */
    public List<Map<String, Object>> getAllTriggersByHostid_new(String hostId, String token) {
        String[] output = new String[]{"description","expression"};
        Map<String, String> initHostItem = TextUtils.getTriggerDataToMap();
        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "trigger.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids", hostId);
                put("expandExpression","true");
                put("output", output);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        //对数据进行翻译封装
        for (int i = 0; i < resultList.size(); i++) {
            Map<String, Object> stringObjectMap = resultList.get(i);
            String name = (String) stringObjectMap.get("description");
            stringObjectMap.put("description", initHostItem.get(name)==null?name:initHostItem.get(name));
        }
        return (List<Map<String, Object>>)responseMap.get("result");
    }

    /**
     * 从xml文件中读取所有触发器表达式及问题
     * @return
     */
    @Override
    public List<Problem> getAllTriggerByXML() {

        Set<Problem> problemsByXML = XmlUtils.analysisXML();
        List<Problem> list = new ArrayList<>(problemsByXML);
        return list;
    }

    /**
     * 自定义的触发器写入 问题 数据库中
     * @param problem 问题类
     * @return 操作成功返回true,失败返回false
     */
    @Override
    public boolean insertProblemIntoDatabase(Problem problem) {
        Integer flag = triggerMapper.insertProblemIntoDatabase(problem);
        if (flag == 1){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 查找自定义的触发器
     * @return
     */
    @Override
    public List<Problem> findComProblems() {
        return triggerMapper.findProblems();
    }

    /**
     * 返回指定主机的触发器列表
     * @param description
     * @return
     */
    @Override
    public boolean isExistTrigger(String description, String hostid) {
        String token = APIUtils.getToken();
        String[] output = new String[]{"description"};
        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "trigger.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids", hostid);
                put("output", output);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        Set<String> nameSet = resultList.stream().map(o -> (String)o.get("description")).collect(Collectors.toSet());

        AtomicBoolean flag = new AtomicBoolean(false);
        HashMap<String, String> triggerDataToMap = TextUtils.getTriggerDataToMap();
        if (triggerDataToMap.containsValue(description)) {
            triggerDataToMap.forEach((k,v) -> {
                if (v.equals(description) && nameSet.contains(k)) {
                    flag.set(true);
                }});
        }
        // 1. 查询当前主机是否有重名触发器
        // 2. 查询汉化的中文是否重名
        if (nameSet.contains(description) || flag.toString().equals("true")) {
            return true;
        }else {
            return false;
        }
    }
}
